//
//  NickNameViewController.m
//  Hai
//
//  Created by gaohaojie on 16/6/17.
//  Copyright © 2016年 wangzijian. All rights reserved.
//

#import "AddTaskViewController.h"
#import "RemindViewController.h"
#import "RemindTimeCell.h"
#import "RemindImageCell.h"
#import "UIImageView+WebCache.h"
#import "CaptureViewController.h"
#import "SJAvatarBrowser.h"
#import "ShowPersonViewController.h"

@interface AddTaskViewController ()
@property (assign, nonatomic) long flag;
@end

@implementation AddTaskViewController
{
    NSInteger _buttonIndex;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden =NO;
    self.navigationItem.title = @"帐户设置";
    [self.collectionView registerClass:[RemindTimeCell class] forCellWithReuseIdentifier:@"RemindTimeCell"];
    [self.collectionImgView registerClass:[RemindImageCell class] forCellWithReuseIdentifier:@"RemindImageCell"];
    [self initDate];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
//是否加载底部导航
- (id)init{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}
//点击空白隐藏键盘
-(void)hideDatePickerView{
    [self.calendarView cancelSelectCurrentDate];
}
- (void)initDate
{
    _arrTimes = [NSMutableArray new];
    NSArray* times = [[NSArray alloc] initWithObjects:@"9",@"12",@"14",nil];
    for (NSString *t in times)
    {
        //if (![image isEqualToString:@""]) {
            [_arrTimes addObject:t];
        //}
    }
    _imagePaths = [NSMutableArray new];
    //NSArray* images = [[NSArray alloc] initWithObjects:@"http://testimg.1000p2p.com/CarouselFigure/20150826140019441291.jpg",@"http://testimg.1000p2p.com/CarouselFigure/20150826140019441291.jpg",@"http://testimg.1000p2p.com/CarouselFigure/20150826140019441291.jpg",nil];
    NSArray* images = [[NSArray alloc] initWithObjects:@"baomazhuangtai.png",@"baomazhuangtai.png",@"baomazhuangtai.png",nil];
    for (NSString *image in images)
    {
        //if (![image isEqualToString:@""]) {
        [_imagePaths addObject:image];
        //}
    }
    [self.collectionImgView reloadData];
    [self.collectionView reloadData];
//    NSString *url=[NSString stringWithFormat:@"%@Loan/GetLoanUploadByType",BaseURL];
//    NSDictionary *parameters = @{@"loanid":_loanid,@"typeid":@"2",@"signature":[Util getSignature:[NSString stringWithFormat:@"%@2",_loanid]]};
//    AFHTTPRequestOperation*op= [_manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSError*error;
//        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
//        //NSLog(@"%@",dic);
//        NSNumber *result = [dic valueForKey:@"Status"];
//        if (error==nil) {
//            if ([result isEqualToNumber:[[NSNumber alloc] initWithInt:1]]) {
//                NSData *jsonData = [[dic valueForKey:@"Data"] dataUsingEncoding:NSUTF8StringEncoding];
//                NSError *err;
//                NSString *UploadImages = [[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err]valueForKey:@"UploadImages"];
//                NSArray* images = [UploadImages componentsSeparatedByString:@","];
//                for (NSString *image in images) {
//                    //     UIImageView * imageView = [[UIImageView alloc]init];
//                    //      [imageView sd_setImageWithURL:[NSURL URLWithString:image]];
//                    //      [_imageArray addObject:imageView];
//                    if (![image isEqualToString:@""]) {
//                        [_imagePaths addObject:image];
//                    }
//                }
//                [self.collectionView reloadData];
//                
//            }else if ([result isEqualToNumber:[[NSNumber alloc] initWithInt:0]]){
//                [[[UIAlertView alloc] initWithTitle: @"发送失败，请稍后再试" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
//                
//                return;
//            }
//        }
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        //NSLog(@"网络异常，error = %@",error.localizedDescription);
//    }];
//    
//    op.responseSerializer = [AFCompoundResponseSerializer serializer];
//    [op start];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.textview resignFirstResponder];
}
-(IBAction)showPerson{
    ShowPersonViewController *user = [[ShowPersonViewController alloc]init];
    [self.navigationController pushViewController:user animated:YES];
}
-(IBAction)save
{
//    NSString *str = self.rtime.text;
//    NSLog(@"%@",str);
    RemindViewController *user = [[RemindViewController alloc]init];
    [self.navigationController pushViewController:user animated:YES];
}

# pragma mark - 点击任意位置键盘消失
- (void)setUpForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view removeGestureRecognizer:singleTapGR];
                }];
}

#pragma mark-点击开始日期
- (IBAction)startTimeView:(id)sender {
    _buttonIndex = 1;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideDatePickerView)];
    [self.view addGestureRecognizer:tapGesture];
    self.calendarView = [[CalendarView alloc]initWithCurrentDate:[NSDate date]];
    self.calendarView.frame =CGRectMake(0, 0, kScreenWidth, kScreenHeight-164);
    self.calendarView.dateDelegate=self;
    [self.view addSubview:self.calendarView];
    [self.calendarView showDatePickerView];
}
#pragma mark-点击结束日期
- (IBAction)endTimeView:(id)sender {
    _buttonIndex = 2;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideDatePickerView)];
    [self.view addGestureRecognizer:tapGesture];
    self.calendarView = [[CalendarView alloc]initWithCurrentDate:[NSDate date]];
    self.calendarView.frame =CGRectMake(0, 0, kScreenWidth, kScreenHeight-164);
    self.calendarView.dateDelegate=self;
    [self.view addSubview:self.calendarView];
    [self.calendarView showDatePickerView];
}

#pragma mark - 返回时间代理
- (void)sendDate:(NSDate *)date{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
    NSString *strDate = [dateFormatter stringFromDate:date];
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    if (_buttonIndex==1) {
        self.showstarttime.text =strDate;
        //_birthday=[dateFormatter2 stringFromDate:date];
    }else if (_buttonIndex==2){
        self.showendtime.text =strDate;
        //_lastday=[dateFormatter2 stringFromDate:date];
    }
}

#pragma mark --UICollectionViewDelegateFlowLayout

//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(collectionView.tag == 1){
        return CGSizeMake(70, 70);
    }
    else{
        return CGSizeMake(70, 30);
    }
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if(collectionView.tag == 1){
        return [self.imagePaths count]+1;//比全局集合多一个模块
    }
    else{
        return [self.arrTimes count];
    }
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)cView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if(cView.tag == 1){
        RemindImageCell * cell =  (RemindImageCell *)[cView dequeueReusableCellWithReuseIdentifier:@"RemindImageCell" forIndexPath:indexPath];
        cell.tag  = _flag;
        _flag++;
        if((long)indexPath.row!=[_imagePaths count]){//如果表格的序号不等于image集合的最大长度
            NSString *image = [_imagePaths objectAtIndex:indexPath.row]; //生产一个应用模块
            //[cell.image sd_setImageWithURL:[NSURL URLWithString:image]];
            cell.image = [_imagePaths objectAtIndex:indexPath.row];
            cell.xbtn.tag=cell.tag;
            cell.xbtn.hidden = NO;
            [cell.xbtn addTarget:self action:@selector(xCell:) forControlEvents:UIControlEventTouchUpInside];
        }else{
            cell.image.image = [UIImage imageNamed:@"shangchuanrenzheng"];
            cell.xbtn.hidden = YES;
        }
        return cell;
    }
    else{
        RemindTimeCell * cell =  (RemindTimeCell *)[cView dequeueReusableCellWithReuseIdentifier:@"RemindTimeCell" forIndexPath:indexPath];
        cell.tag  = _flag;
        _flag++;
        //if((long)indexPath.row!=[_imagePaths count]){//如果表格的序号不等于image集合的最大长度
        NSString *image = [_arrTimes objectAtIndex:indexPath.row]; //生产一个应用模块
        //[cell.image sd_setImageWithURL:[NSURL URLWithString:image]];
        // [cell.image setImage:imageView.image];
        cell.timetext.text = [NSString stringWithFormat:@"%@:00",image];
        cell.xbtn.tag=cell.tag;
        [cell.xbtn addTarget:self action:@selector(xCell:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView.tag == 1) {
        RemindImageCell *cell =(RemindImageCell * ) [collectionView cellForItemAtIndexPath:indexPath];
        if((long)indexPath.row==[_imagePaths count]){//如果表格的序号 等于image集合的最大长度
            [self choseButtonClicked];
        }else{
            if (cell.image.image!=nil) {
                [SJAvatarBrowser showImage:cell.image];//调用方法
            }
            return;
        }
    }
    
    
}
-(void)xCell:(UIButton *)btn{
    //取出点击的cell
    
    RemindTimeCell *c = (RemindTimeCell * )[_collectionView viewWithTag:btn.tag];
    NSIndexPath *ffIndexPath = [_collectionView indexPathForCell:c];
    NSUInteger didPosition = ffIndexPath.row;
    //  [_imageArray removeObjectAtIndex:didPosition];
    [_arrTimes removeObjectAtIndex:didPosition];
    
    NSMutableArray *indexPathArray = [NSMutableArray array];
    NSIndexPath *tempIndexPath = [NSIndexPath indexPathForRow:didPosition inSection:0];
    [indexPathArray addObject:tempIndexPath];
    [_collectionView deleteItemsAtIndexPaths:indexPathArray];
}

#pragma mark-添加提醒时间
- (IBAction)remindTimeView:(id)sender {
    _buttonIndex = 3;
    HourPickViewController *pickVC = [[HourPickViewController alloc]init];
    [self addChildViewController:pickVC];
    pickVC.dayDataDelegate = self;
    pickVC.view.frame =CGRectMake(0, 0, kScreenWidth, kScreenHeight-64);
    [self.view addSubview:pickVC.view];
}

#pragma mark - 返回提醒时间代理
- (void)sendDayData:(NSString * __nullable)dayData dayDataIndex:(NSString * __nullable)dayDataIndex{
    if (_buttonIndex==3) {
        //判断是否在数组中存在
        if([_arrTimes containsObject:dayData] == NO)
        {
            //添加到数组中
            [_arrTimes addObject:dayData];
            //给数组排序
            [_arrTimes sortUsingComparator:^NSComparisonResult(__strong id obj1,__strong id obj2){
                NSString *str1=(NSString *)obj1;
                NSString *str2=(NSString *)obj2;
                return [str1 compare:str2];
            }];
            //刷新collectionview
            [self.collectionView reloadData];
        }
    }
}


//弹出选项列表选择图片来源
- (void)choseButtonClicked{
    UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从手机相册选择", nil];
    [chooseImageSheet showInView:self.view];
}

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
    
}
#pragma mark UIActionSheetDelegate Method
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    
    switch (buttonIndex) {
        case 0://Take picture
            
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                
            }else{
                //NSLog(@"模拟器无法打开相机");
            }
            //            [self presentModalViewController:picker animated:YES];
            [self presentViewController:picker animated:YES completion:^(void){
                // Code
            }];
            
            break;
            
        case 1://From album
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //            [self presentModalViewController:picker animated:YES];
            [self presentViewController:picker animated:YES completion:^(void){
                // Code
            }];
            break;
            
        default:
            
            break;
    }
}

#pragma 拍照选择照片协议方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    NSData *data;
    
    if ([mediaType isEqualToString:@"public.image"]){
        
        //切忌不可直接使用originImage，因为这是没有经过格式化的图片数据，可能会导致选择的图片颠倒或是失真等现象的发生，从UIImagePickerControllerOriginalImage中的Origin可以看出，很原始，哈哈
        UIImage *originImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        //图片压缩，因为原图都是很大的，不必要传原图
        UIImage *scaleImage = [self scaleImage:originImage toScale:0.3];
        
        //以下这两步都是比较耗时的操作，最好开一个HUD提示用户，这样体验会好些，不至于阻塞界面
        if (UIImagePNGRepresentation(scaleImage) == nil) {
            //将图片转换为JPG格式的二进制数据
            data = UIImageJPEGRepresentation(scaleImage, 1);
        } else {
            //将图片转换为PNG格式的二进制数据
            data = UIImagePNGRepresentation(scaleImage);
        }
        
        //将二进制数据生成UIImage
        UIImage *image = [UIImage imageWithData:data];
        
        //将图片传递给截取界面进行截取并设置回调方法（协议）
        CaptureViewController *captureView = [[CaptureViewController alloc] init];
        captureView.delegate = self;
        //        captureView.type=1;
        
        captureView.image = image;
        //隐藏UIImagePickerController本身的导航栏
        //        picker.navigationBar.hidden = YES;
        [picker pushViewController:captureView animated:YES];
        
    }
}
#pragma mark- 缩放图片
-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}


-(void)passImage:(UIImage *)image
{
    NSMutableArray *indexPathArray = [NSMutableArray array];
    NSIndexPath *tempIndexPath = [NSIndexPath indexPathForRow:_imagePaths.count!=0?_imagePaths.count:0 inSection:0];
    [indexPathArray addObject:tempIndexPath];
    [_imagePaths insertObject:image atIndex:tempIndexPath.row];
    [_collectionImgView insertItemsAtIndexPaths:indexPathArray];
    

//    _HUD = [[MBProgressHUD alloc]initWithView:self.view];
//    _HUD.labelFont = [UIFont systemFontOfSize:12.0f];
//    [self.view addSubview:_HUD];
//    _HUD.mode =MBProgressHUDModeIndeterminate;
//    _HUD.labelText =@"正在提交，请稍候";
//    _HUD.dimBackground = YES;
//    
//    [_HUD show:YES];
//    NSString *url=[NSString stringWithFormat:@"%@Loan/LoanUpload",BaseURL];
//    NSDictionary *parameters = @{@"loanid":_loanid,@"dirname":@"Income"};
//    AFHTTPRequestOperation *op = [_manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//        NSData *imageData = UIImagePNGRepresentation(image);
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        formatter.dateFormat = @"yyyyMMddHHmmss";
//        NSString *str = [formatter stringFromDate:[NSDate date]];
//        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
//        
//        // 上传图片，以文件流的格式
//        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
//        
//    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        _HUD.hidden = YES;
//        NSError*error;
//        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject
//                                                          options:NSJSONReadingAllowFragments error:&error];
//        NSMutableArray *indexPathArray = [NSMutableArray array];
//        NSIndexPath *tempIndexPath = [NSIndexPath indexPathForRow:_imagePaths.count!=0?_imagePaths.count:0 inSection:0];
//        [indexPathArray addObject:tempIndexPath];
//        //  UIImageView * imageView = [[UIImageView alloc]init];
//        // imageView.image = image;
//        //  [_imageArray insertObject:imageView atIndex:tempIndexPath.row];
//        [_imagePaths insertObject:[dic valueForKey:@"Data"] atIndex:tempIndexPath.row];
//        [_collectionView insertItemsAtIndexPaths:indexPathArray];
//        
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        [[[UIAlertView alloc] initWithTitle: @"网络异常" message:nil
//                                   delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
//    }];
//    op.responseSerializer = [AFCompoundResponseSerializer serializer];
//    [op start];
}

@end
